define(['template/who/indexTpl','wx','wx.ajax','wx.tpl','wx.pop','wx.upload','wx.cookie','wx.validator','vendor/bootstrap-typeahead','vendor/bootstrap-datetimepicker'],function(tpl,wx){
    var who = {};
    var emData = {};
    var isWrite;
    var userId = wx.cookie('userid');
    function init(id,w){
        isWrite = w;
        var t = new Date().getTime();
        $.when(
            $.ajax('/res/css/who.css?_='+t),
            $.ajax('/res/css/bootstrap-datetimepicker.css?_='+t)
        ).done(function(whoCss,dateCss){
            $('<style type="text/css">').append(whoCss,dateCss).appendTo('head');
            getDetail(userId);

        });
	}

	function getDetail(id){
        $('#window-frame-who').html(tpl.search);
        $('#Js-who-search').typeahead({
            items:10,
            ajax: {
                url:'/who/search',
                triggerLength: 1,
            },
            grepper:function(data){
                return data;
            },
            itemSelected:function(item,id){
                getDetail(id);
            }
        });
		wx.sendData('/who/detail','id='+id,function(data){
            emData = data;
            data.data.isWrite=isWrite;
            data.data.canEdit= userId == data.data.id;
            $('.who-content,.who-photo').remove();
			$('#window-frame-who').append(wx.tpl(tpl.detail,data.data));
            setEvent();
		});
	}

    function setEvent(){
        $('#window-frame-who').find('dl').hover(function() {
            $(this).find('.Js-item-edit').show();
        }, function() {
            $(this).find('.Js-item-edit').hide();
        });

        wx.upload($('input[name="file"]'));
        $('input[name="file"]').on('upload',function(event,data){
            wx.sendData('/who/update','id='+emData.data.id+'&data={"photo":"'+data.path+'"}');
        });
        
        $('#window-frame-who').find('.Js-item-edit').click(function() {
            $(this).prev().addClass('edit').prop('contenteditable',true).focus().blur(function() {
                if(wx.validator.rule[$(this).data('type')]($(this).text())){
                    updateData($(this));
                    $(this).removeClass('edit edit-error').prop('contenteditable',false);
                } else {
                    $(this).addClass('edit-error');
                }
            });
        });

        $('#Js-advanceSetting').click(function(){
            wx.sendData('/permission/get-list',advanceSetting);
        });

        $('#Js-addEmp').click(function(){

        $.when(
            $.ajax('/permission/get-list',{dataType:'json'}),
            $.ajax('/department/getall',{dataType:'json'})).done(function(perData,depData){
                initCreateEmp(perData[0],depData[0]);
            });
        });
    }

    function initCreateEmp(perData,depData){
        var sir_id = null,
            permissionId = perData.result[0].id,
            departmentName = depData.data[0].name;

        $('#window-frame-who').html(wx.tpl(tpl.addNew,{perlist:perData,deplist:depData.data}));
        wx.validator();
        $('input[name="join_time"]').datetimepicker({
            format: 'yyyy-mm-dd',
            weekStart: 1,
            todayBtn:  1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0
        });
        $('#Js-who-sir').typeahead({
            items:10,
            ajax: {
                url:'/who/search',
                triggerLength: 1,
            },
            grepper:function(data){
                return data;
            },
            itemSelected:function(item,id){
                sir_id = id;
            }
        });

        $('form[name="who-add"]').on('validator:before',function(){
            $('#Js-addNew-error').text('');
            if($('input[name="join_time"]').val().length == 0){
                $('#Js-addNew-error').text('请选择入职时间');
                return false;
            }
            if(sir_id == null){
                $('#Js-addNew-error').text('请选择员工上级');
                return false; 
            }
            $(this).find('input[name="sir_id"]').val(sir_id);
            $(this).find('input[name="permission"]').val($(this).find('input[name="permission"]').val()||permissionId);
            $(this).find('input[name="department"]').val($(this).find('input[name="department"]').val()||departmentName);
            return true;
        });
        $('form[name="who-add"]').on('validator',function(event,data){
            if(data.status != 1){
                $('#Js-addNew-error').text(data.info);
            } else {
                getDetail(data.result.id);
            }
        });

        $('#Js-addEmp-back').click(function(){
            getDetail(userId);
        });

        $('.dropdown-menu').delegate('li','click',function(){
            var item = $(this).parent().prev().find('a');
            var type = $(this).find('a').data('typte');
            var value = $(this).find('a').data('value');
            $('form[name="who-add"]').find('input[name="'+type+'"]').val(value);
            item.text($(this).find('a').text());
        });
    }

    function advanceSetting(data){
        var permission=emData.data.permission,sir=emData.data.sir_id;
        $('#window-frame-who').html(wx.tpl(tpl.advance,{perlist:data,info:emData.data}));
        $('.dropdown-menu').delegate('li','click',function(){
            var item = $(this).parent().prev().find('a');
            permission = $(this).find('a').data('id');
            item.text($(this).find('a').text());
        });
        $('#Js-advance-addBack').click(function(){
            getDetail(userId);
        });
        $('#Js-advance-confirm').click(function(){
            wx.sendData('/who/update','id='+emData.data.id+'&data={"permission":"'+permission+'","sir_id":"'+sir+'"}').success(function(){
                getDetail(emData.data.id);
            });
        });
        $('#Js-advance-sir').typeahead({
            items:10,
            ajax: {
                url:'/who/search',
                triggerLength: 1,
            },
            grepper:function(data){
                return data;
            },
            itemSelected:function(item,id){
                sir = id;
            }
        });
    }

    function updateData($item){
        wx.sendData('/who/update','id='+emData.data.id+'&data={"'+$item.data('type')+'":"'+$item.text()+'"}');
    }

    who.init = init;
    return who;
});